FlutterはBuildContextなしでナビゲート
1814 ワード
import 'package:flutter/material.dart';
NavigationService navigationService;
void main() {
navigationService = NavigationService();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigationService.navigatorKey,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
),
body: Center(
child: RaisedButton(
child: Text('to screen2'),
onPressed: () {
navigationService.navigateTo(MaterialPageRoute(
builder: (context) => Screen2(),
));
},
),
),
);
}
}
class Screen2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('screen2'),
),
body: Center(
child: RaisedButton(
child: Text('back'),
onPressed: () {
navigationService.goBack();
},
),
),
);
}
}
class NavigationService {
NavigationService() {
navigatorKey = GlobalKey();
}
GlobalKey navigatorKey;
Future navigateTo(Route route) {
return navigatorKey.currentState.push(route);
}
bool goBack() {
return navigatorKey.currentState.pop();
}
}
転載先:https://www.cnblogs.com/ajanuw/p/11506619.html