備忘録
Flutter初心者
Flutter Doc JPのBottomNavigationBarで軽く詰まったので
ここが抜けてたら、初心者はわからへん
MainPageがウィジェットじゃないからって怒られる。
↓
MainPageのStatefullWidget作る
↓
class MyAppのhome にMainPage(),追加
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MainPage(),
);
}
}
class MainPage extends StatefulWidget{
@override
_MainPageState createState () => _MainPageState();
}
以下全文
main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MainPage(),
);
}
}
class MainPage extends StatefulWidget{
@override
_MainPageState createState () => _MainPageState();
}
class _MainPageState extends State<MainPage> {
int _currentIndex = 0;
final _pageWidgets = [
PageWidget(color:Colors.white, title:'Home'),
PageWidget(color:Colors.blue, title:'Album'),
PageWidget(color:Colors.orange, title:'Chat'),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BottomNavigationBar'),
),
body: _pageWidgets.elementAt(_currentIndex),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.photo_album), title: Text('Album')),
BottomNavigationBarItem(icon: Icon(Icons.chat), title: Text('Chat')),
],
currentIndex: _currentIndex,
fixedColor: Colors.blueAccent,
onTap: _onItemTapped,
type: BottomNavigationBarType.fixed,
),
);
}
void _onItemTapped(int index) => setState(() => _currentIndex = index );
}
class PageWidget extends StatelessWidget {
final Color color;
final String title;
PageWidget({Key key, this.color, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
color: color,
child: Center(
child: Text(
title,
style: TextStyle(
fontSize: 25,
),
),
),
);
}
}