如何使用go_router使Flutter网页可滚动?

wwwo4jvm  于 2023-06-30  发布在  Flutter
关注(0)|答案(1)|浏览(168)

我用go_router包构建了一个网页。有一个ShellRoute可以使标题图像和标题导航栏对所有页面都是静态的。我不能使页面垂直滚动,但给出了渲染问题,无论我把SingleChildScrollView(同时删除扩展)。
下面是代码:

  1. import 'package:flutter/material.dart';
  2. import 'package:go_router/go_router.dart';
  3. void main() {
  4. runApp(MyApp());
  5. }
  6. final GoRouter _router = GoRouter(
  7. initialLocation: '/',
  8. routes: [
  9. ShellRoute(
  10. builder: (context, state, child) {
  11. return Scaffold(
  12. body: Padding(
  13. padding:EdgeInsets.symmetric(horizontal: 200),
  14. child: Column(
  15. children: [
  16. Image.asset('images/Banner.png'), //header image
  17. Container( //header menu
  18. color: Colors.blue,
  19. height: 100,
  20. ),
  21. Expanded(
  22. child: child,
  23. ),
  24. ]
  25. ),
  26. ),
  27. );
  28. },
  29. routes: [
  30. GoRoute(
  31. path: "/",
  32. builder: (context, state) {
  33. return HomePage();
  34. },
  35. ),
  36. ],
  37. ),
  38. ],
  39. );
  40. class MyApp extends StatelessWidget {
  41. // This widget is the root of your application.
  42. @override
  43. Widget build(BuildContext context) {
  44. return MaterialApp.router(
  45. routerConfig: _router,
  46. title: 'Test',
  47. theme: ThemeData(
  48. primarySwatch: Colors.blue,
  49. ),
  50. );
  51. }
  52. }
  53. class HomePage extends StatelessWidget {
  54. /// Constructs a [HomeScreen]
  55. HomePage({super.key});
  56. @override
  57. Widget build(BuildContext context) {
  58. print('hit');
  59. return Scaffold(
  60. body: Column(
  61. children: [
  62. Container(height: 200, color: Colors.purple),
  63. Container(height: 300, color: Colors.green),
  64. Container(height: 400, color: Colors.red),
  65. ]
  66. )
  67. );
  68. }
  69. }

另一个有趣的事情是,类HomePage在每次热重启时被触发3次。如果有像从API加载数据这样的网络活动,它将触发3次,使加载时间延长3倍。

utugiqy6

utugiqy61#

您只需将HomePage中的列 Package 为SingleChildScrollView,如下所示:

  1. class HomePage extends StatelessWidget {
  2. /// Constructs a [HomeScreen]
  3. HomePage({super.key});
  4. @override
  5. Widget build(BuildContext context) {
  6. print('hit');
  7. return Scaffold(
  8. body: SingleChildScrollView(
  9. child: Column(
  10. children: [
  11. Container(height: 200, color: Colors.purple),
  12. Container(height: 300, color: Colors.green),
  13. Container(height: 400, color: Colors.red),
  14. ]
  15. ),
  16. )
  17. );
  18. }
  19. }

不应删除Expanded
关于重建。不知道为什么它发生了多次,但它不应该是一个问题。无论如何,你都不应该在构建方法中从API中获取数据。您应该始终以这样一种方式实现build方法,即多次调用该方法不会产生副作用。通常情况下,您有一个StatefulWidget,然后在initState中执行API调用,而不是在build

展开查看全部

相关问题