Flutter MaterialPageRoute 导航到黑色背景屏幕时如何解决?

Rat*_*rty 4 mobile android ios flutter

我第一次在我的一个报纸应用项目中使用 Flutter。

问题发生时,我尝试从导航main.dartnewsfeed_for_other_category.dart使用MaterialPageRoute从我的Drawer。在该屏幕中,它显示新闻,但背景为黑色。但是在newsfeed_screen.dart我的身体中调用的屏幕中main.dart它显示得很好。

我在下面发布代码。

main.dart

import 'package:flutter/material.dart';
import './SizeConfig.dart';
import './screens/newsfeed_screen.dart';
import 'package:curved_navigation_bar/curved_navigation_bar.dart';
import 'factory/widget_factory.dart';
import 'widgets/top_news_widget.dart';
import 'package:splashscreen/splashscreen.dart';
import './widgets/drawer.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Newspaper App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        //backgroundColor: Colors.lightGreenAccent,
      ),
      home: MyHomePage(title: 'The Business Standard'),
      routes: <String, WidgetBuilder> {
        '/screen1': (BuildContext context) => new NewsFeedScreen(216, 5, "Top News"),
        '/screen2' : (BuildContext context) => new NewsFeedScreen(4, 7, "National"),
        '/screen3' : (BuildContext context) => new NewsFeedScreen(13, 70, "International"),
        /*'/screen4' : (BuildContext context) => new Screen4()*/
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: '_MainScreenKey');

  Widget build(BuildContext context) {
    return SplashScreen(
        seconds: 3,
        navigateAfterSeconds: AfterSplash(),
        title: Text(
          'The Business Standard',
          style: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 20.0
          ),
        ),
        image: Image.asset(
            'assets/TBS_logo.jpg',
        ),
        backgroundColor: Colors.white,
        styleTextUnderTheLoader: TextStyle(),
        photoSize: 100.0,
        onClick: ()=>print("Flutter Egypt"),
        loaderColor: Colors.red
    );
  }
}

class AfterSplash extends StatefulWidget {

  @override
  _AfterSplashState createState() => _AfterSplashState();
}

class _AfterSplashState extends State<AfterSplash> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(debugLabel: '_MainScreenKey');

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Image.asset(
              'assets/TBS.png',
              fit: BoxFit.cover,
              height: 45,
            )
          ],
        ),
        leading: IconButton(
          icon: Icon(Icons.dehaze),
          color: Colors.black,
          onPressed: () => _scaffoldKey.currentState.openDrawer(),
        ),
      ),
      drawer: SideDrawer(),
      body: NewsFeedScreen(22, 71, "Sports"),
      bottomNavigationBar: CurvedNavigationBar(
        backgroundColor: const Color(0xFF2b4849),
        items: <Widget>[
          Icon(Icons.bookmark, size: 30,),
          Icon(Icons.perm_identity, size: 30,),
          Icon(Icons.settings, size: 30,),
        ],
        onTap: (index) {
          if(index == 2) {
            _scaffoldKey.currentState.showSnackBar(const SnackBar(
                content: const Text('Will open Settings menu')));
          } else if(index == 0) {
            _scaffoldKey.currentState.showSnackBar(const SnackBar(
                content: const Text('Implement Bookmark function')));
          } else {
            _scaffoldKey.currentState.showSnackBar(const SnackBar(
                content: const Text('Will show User profile and information')));
          }
        },
      ),
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

newsfeed_for_other_category.dart,我导航到的页面,这是黑色背景出现的地方。

import 'package:flutter/material.dart';
import '../SizeConfig.dart';
import '../widgets/headlines.dart';
import '../widgets/secondary_headlines.dart';
import '../widgets/listed_news.dart';
import '../models/NewsPost.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:developer';
import '../screens/newsPost_details.dart';
import '../screens/newsfeed_for_specific_category.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import '../transition_animation_routes/ScaleTransitionRoute.dart';
import '../widgets/top_news_widget.dart';

class NewsfeedForOtherCategory extends StatefulWidget {
  int categoryId;
  int childrenCategoryId;
  String categoryName;

  NewsfeedForOtherCategory(this.categoryId, this.childrenCategoryId, this.categoryName);
  @override
  _NewsfeedForOtherCategoryState createState() => _NewsfeedForOtherCategoryState(this.categoryId, this.childrenCategoryId, this.categoryName);
}

class _NewsfeedForOtherCategoryState extends State<NewsfeedForOtherCategory> {
  int categoryId;
  int childrenCategoryId;
  String categoryName;

  _NewsfeedForOtherCategoryState(this.categoryId, this.childrenCategoryId, this.categoryName);

  bool _isRequestSent = false;
  List<NewsPost> newsPostList = [];

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);

    if(!_isRequestSent) {
      _sendRequest();
    }

    return Container(
      alignment: Alignment.center,
      child: !_isRequestSent
          ? CircularProgressIndicator()
          : Container(
        child: ListView.builder(
            itemCount: newsPostList.length,
            scrollDirection: Axis.vertical,
            itemBuilder: (BuildContext context, int index) {
              return _getNewsPostWidgets(index);
            }
        ),
      ),
    );
  }

  void _sendRequest() async {
    String url = "https://tbsnews.net/json/category/news/"+this.categoryId.toString()+"/"+this.childrenCategoryId.toString()+"";
    http.Response response = await http.get(url);
    List<dynamic> decode = json.decode(response.body);
    log('response: $response');
    List results = decode[0]['items'];
    for (var jsonObject in results) {
      var post = NewsPost.getNewsPostFromAPI(jsonObject);
      newsPostList.add(post);
      print(post);
    }
    setState(() => _isRequestSent = true);
  }

  Widget _getNewsPostWidgets(int index) {
    var newsPost = newsPostList[index];

    if(index < this.newsPostList.length) {
      if(index == 0) {
        return GestureDetector(
            onTap: () {
              Navigator.push(
                  context,
                  ScaleTransitionRoute(
                      page: NewsPostDetails(newsPostList, index)
                  )
              );
            },
            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  //constraints: BoxConstraints(minWidth: double.infinity, maxWidth: double.infinity),
                  constraints: BoxConstraints.expand(
                      width: double.infinity,
                      height: 40
                  ),
                  color: const Color(0xFF2b4849),
                  child: Text(
                    this.categoryName,
                    style: TextStyle(
                        fontSize: 33,
                        color: Colors.white
                    ),
                  ),
                ),
                BlockHeadline(newsPost)
              ],
            )
        );
      }
      else {
        return GestureDetector(
          onTap: () {
            Navigator.push(
                context,
                ScaleTransitionRoute(
                    page: NewsPostDetails(newsPostList, index)
                )
            );
          },
          child: ListedNews(newsPost),
        );
      }
    }
    else {
      return Container(
        color: const Color(0xFF2b4849),
        child: index == 3 ? FlatButton(
          child: Text(
            "Load More",
            style: TextStyle(
                color: Colors.white
            ),
          ),
          onPressed: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (BuildContext context) => NewsFeedForSpecificCategory(newsPostList)
                )
            );
          },
        ) : Container(),
      );
    }
  }

  openNewsPostDetails(List<NewsPost> newsPostList, int index) {
    Navigator.push(
        context,
        ScaleTransitionRoute(
            page: NewsPostDetails(newsPostList, index)
        )
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

抽屉.dart

import 'package:flutter/material.dart';
import '../SizeConfig.dart';
import '../screens/newsfeed_for_other_category.dart';

class SideDrawer extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return SizedBox(
      width: SizeConfig.safeBlockHorizontal*50,
      child: Theme(
        data: Theme.of(context).copyWith(canvasColor: const Color(0xFF2b4849)),
        child: Drawer(
          child: ListView(
            children: <Widget>[
              ListTile(
                title: Text(
                  'Top News',
                  style: TextStyle(
                      fontSize: 20,
                      color: Colors.white
                  ),
                ),
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (BuildContext context) => NewsfeedForOtherCategory(216, 5, "Top News")
                      )
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的主屏幕中,它newsfeed_screen.dartAfterSplashState小部件的主体中被调用,main.dart如下所示,这就是它应该是什么样子。

在此处输入图片说明

但是在NewsfeedForOtherCategory我使用导航到的屏幕中,drawer看起来像下面的黑色背景。

在此处输入图片说明

我曾尝试使用Navigator.of(context, rootNavigator: true).pushNamed('/route')andpushReplacementNamed()代替MaterialPageRoute. 但是没有用。

这是我发现的一个相关问题,我尝试了他们提供的解决方案,但对我不起作用。

还要提一下,我要导航到的页面没有MaterialApp小部件,只有小部件才有main.dart。所以应该没有问题。

我正在使用 Ubuntu 16.04 机器。

你的一些线索将是无价的。非常感谢您的时间。

Cra*_*Cat 5

NewsfeedForOtherCategory页面是黑色的,因为它没有Material容器。您可以简单地用Material小部件或Scaffold(它具有一些附加功能,如抽屉、浮动操作按钮)包装它。

从您的屏幕截图中,我可以看到一些小部件被通知栏溢出。您可以使用SafeArea内部Material或内部bodyScaffold克服这一点。