0%

Flutter 021 - Presentation AutoRouter (part5)

前言

Hi, 今天要在我們的專案裡面加入場景的路由,這樣可以方便管理我們每個場景,教學內容只會擷取片段程式碼,建議大家搭配完整程式碼來練習。

完整程式碼

需要準備的知識

AutoRouter

創建一個路徑並設置為初始路徑,完成後就可以執行生成檔案的指令,你將會得到router.gr.dart檔案,並且終端機會顯示成功。

1
$ flutter pub run build_runner watch --delete-conflicting-outputs
1
2
3
4
5
6
7
8
9
10
11
12
13
import 'package:auto_route/auto_route.dart';
import 'package:stunning_tribble/presentation/screens/home/home_screen.dart';

@MaterialAutoRouter(
replaceInRouteName: 'Page,Route',
routes: <AutoRoute>[
AutoRoute(
page: HomeScreen,
initial: true,
),
],
)
class $AppRouter {}

接著宣告一個AppRouter()傳入APP內使用,如果改完後APP報錯,重新啟動後就可以使用了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await ConfigReader.initializeApp(Environment.dev);
final AppRouter appRouter = AppRouter();
runApp(
MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => ThemeBloc(),
),
],
child: MyApp(
appRouter: appRouter,
),
),
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class MyApp extends StatelessWidget {
final AppRouter _appRouter;

const MyApp({
Key? key,
required AppRouter appRouter,
}) : _appRouter = appRouter,
super(key: key);

@override
Widget build(BuildContext context) {
return BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) {
return MaterialApp.router(
debugShowCheckedModeBanner: ConfigReader.config().DEBUG,
title: 'Flutter Demo',
theme: state.themeData,
darkTheme: ThemeData(),
routerDelegate: _appRouter.delegate(),
routeInformationParser: _appRouter.defaultRouteParser(),
builder: (context, router) => router!,
);
},
);
}
}