简体   繁体   English

Flutter Page 每次在导航弹出时都会重新加载

[英]Flutter Page Keeps reloading every time on navigation pop

I am building a sample app to display a list of news using flutter framework.我正在构建一个示例应用程序以使用 flutter 框架显示新闻列表。 The app has two pages one is home and details page.该应用程序有两个页面,一个是主页和详细信息页面。 When I pop from the detailed page the home page keeps reloading every time.当我从详细页面弹出时,主页每次都会重新加载。

I have used FutureBuilder widget to load news and display as list of cards and for detail page i am using a webview fluggin for flutter to load the full news from a url.我使用 FutureBuilder 小部件加载新闻并显示为卡片列表,对于详细信息页面,我使用 webview fluggin for flutter 从 url 加载完整新闻。

The main page code is:主页面代码为:

import 'package:flutter/material.dart';
import 'package:flutter_post/detail_page.dart';
import 'package:flutter_post/model/news.dart';
import 'package:flutter_post/services/news_services.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: 'Flutter News',
      debugShowCheckedModeBanner: false,
      theme: new ThemeData(primaryColor: Colors.white, fontFamily: 'Raleway'),
      home: NewsPage(title: 'Flutter News'),
    );
  }
}

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

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

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

class _NewsPageState extends State<NewsPage> {

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Align(alignment: Alignment.center, child: Text(widget.title),),
        elevation: 0.1,
        backgroundColor: Colors.white,
      ),
      backgroundColor: Colors.white,
      body: _newsPage(),
    );
  }

  Widget _newsPage() {
    return FutureBuilder<News>(
        future: loadNews(), builder: (context, snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.none:
        case ConnectionState.waiting:
          return _loadingRow();
        case ConnectionState.done:
          if (snapshot.hasError) {
            return _errorRow();
          }
          return _newsList(snapshot.data.articles);
        case ConnectionState.active:
      }
    });
  }

  Widget _newsList(List<Article> articles) {
    return ListView.builder(itemCount: articles.length,
        itemBuilder: (BuildContext context, int index) {
          return InkWell(child: Card(
            elevation: 8.0,
            clipBehavior: Clip.antiAlias,
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(5.0))),
            margin: EdgeInsets.only(left: 15.0, right: 15.0, bottom: 15.0),
            child: _cardItem(articles[index]),),
            onTap: () {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: (context) =>
                          DetailPage(article: articles[index],)));
            },);
        });
  }

  Widget _errorRow() {
    return Align(alignment: Alignment.center,
      child: Text(
          "Error!", style: _textStyle(Colors.black38, FontWeight.bold, 20.0)),);
  }

  Widget _cardItem(Article article) {
    return new Container(
      height: 250.0,
      child: new Stack(
        children: <Widget>[
          _cardBackground(article),
          _cardContent(article)
        ],
      ),
    );
  }

  Widget _cardBackground(Article article) {
    return new Container(
      decoration: new BoxDecoration(
        image: new DecorationImage(
            colorFilter: new ColorFilter.mode(
                Colors.black.withOpacity(0.6),
                BlendMode.luminosity),
            image: new NetworkImage(
                article.urlToImage != null ? article.urlToImage : null),
            fit: BoxFit.cover
        ),
      ),
    );
  }

  Widget _cardContent(Article article) {
    return new Align
      (child: Container(
      alignment: Alignment.bottomCenter,
      padding: EdgeInsets.all(10),
      child: new Column(mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Flexible(child: new Text(article.title, maxLines: 2,
              style: _textStyle(Colors.white, FontWeight.bold, 20.0)),),
          Padding(padding: EdgeInsets.only(top: 5.0),),
          Flexible(child: new Text(publishedBy(article),
            style: _textStyle(Colors.white, FontWeight.w400, 12.0),),)
        ],
      ),
    ), alignment: Alignment.bottomLeft,
    );
  }

  String publishedBy(Article article) {
    return "published by " + article.source.name;
  }

  TextStyle _textStyle(Color color, FontWeight weight, double size) {
    return TextStyle(color: color, fontWeight: weight, fontSize: size);
  }

  Widget _loadingRow() {
    return Align(
      alignment: Alignment.center, child: CircularProgressIndicator(),);
  }
}

The detailed page code is:详细页面代码为:

import 'package:flutter/material.dart';
import 'package:flutter_post/model/news.dart';
import 'package:share/share.dart';
import 'package:webview_flutter/webview_flutter.dart';

class DetailPage extends StatelessWidget {
  final Article article;

  DetailPage({this.article});

  void shareUrl() {
    Share.share('Read the full news from ' + article.url);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: new InkWell(
          onTap: () {
            Navigator.pop(context);
          },
          child: new Icon(Icons.close, color: Colors.black),),
        elevation: 0.1,
        title: new Text(article.url),
        backgroundColor: Colors.white,
      ),
      body: WebView(initialUrl: article.url,),
      floatingActionButton: FloatingActionButton(
        child: new Icon(Icons.share, color: Colors.white),
        onPressed: shareUrl,),
    );
  }
}

What I want is that every time I come back from the detail page the home page should not refresh/reload.我想要的是,每次我从详细信息页面返回时,主页都不应刷新/重新加载。 Any help is much appreciated.任何帮助深表感谢。

I think I know the answer to your problem.我想我知道你的问题的答案。

  1. create a news state/object in _NewsPageState_NewsPageState中创建新闻状态/对象
  2. use initState to load your data loadNews()使用 initState 加载数据loadNews()
  3. reference the future object in your FutureBuilder<News>FutureBuilder<News>中引用未来对象

Sample Code:示例代码:

class _NewsPageState extends State<NewsPage> {

  Future<News> _myNews;

  @override
  void initState() {
    _myNews = loadNews();
  }

  ...

  Widget _newsPage() {
    return FutureBuilder<News>(
      future: _myNews,
      builder: (context, snapshot) {
        ...
      }
    );
  }

  ...
} 

I hope it helps you:)我希望它能帮助你:)

Yours Glup3你的 Glup3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM