目次
先に使うScreenを作る
今回は、2画面の切り替えをしたいと思います。
IndexedStack(切り替える用のクラス)とHomeScreen,MenuScreenを作っていきます。
HomeScreen
StatefulWidgetを使い、
routeで使う「static String id = ‘home_screen’;」を記入し
textを書いただけ。
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
// main.dartのrouteで使う。
static String id = 'home_screen';
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
child: Text("HomeScreen_Now"),
),
);
}
}
MenuScreen
homeScreenと同じ
import 'package:flutter/material.dart';
class MenuScreen extends StatefulWidget {
// main.dartのrouteで使う。
static String id = 'menu_screen';
@override
_MenuScreenState createState() => _MenuScreenState();
}
class _MenuScreenState extends State<MenuScreen> {
@override
Widget build(BuildContext context) {
return Center(child: Container(
child: Text('MenuScreen_Now'),
));
}
}
IdexedeStackを作る
BottomNavigationBarとIndexeStackを書き込む。
Homeとmenuをimportするのを忘れずに。
import 'package:flutter/material.dart';
import 'package:indexed_stack/home_screen.dart';
import 'package:indexed_stack/menu_screen.dart';
class IndexedStackBar extends StatefulWidget {
static String id = 'indexed_stack_bar';
@override
_IndexedStackBarState createState() => _IndexedStackBarState();
}
class _IndexedStackBarState extends State<IndexedStackBar> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body:IndexedStack(
index: _selectedIndex,
children: <Widget>[
HomeScreen(),
MenuScreen(),
],
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
icon: Icon(
Icons.home,
color: Colors.green,
),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(
Icons.favorite_border,
color: Colors.pinkAccent,
),
title: Text('Menu'),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
// onTap: _onItemTapped,
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
}),
);
}
}
main.dartにrouteを書き込み、各Screenをimport
import 'package:flutter/material.dart';
import 'package:indexed_stack/home_screen.dart';
import 'package:indexed_stack/menu_screen.dart';
import 'indexed_stack_bar.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: IndexedStackBar.id,
// LoginScreen.id,
routes: {
// 情報サイト側
HomeScreen.id: (context) => HomeScreen(),
MenuScreen.id: (context) => MenuScreen(),
// Menu画面
IndexedStackBar.id: (context) => IndexedStackBar(),
},
);
}
}