Pars
Pars

Reputation: 5272

Losing data while navigating screens in Flutter

I am new to Flutter and just started to make a tiny little app which takes a list of Top Movies from a server using an async request. and when I tap on top of each one of list items, then it navigates me to another screen to show some details about the movie.

But there is a problem, when I tap on any item to see it's details, inside the details page, when I press back, in the first page, it just loads data again which is not a good user experience. also uses more battery and bandwidth for each request.

I don't know if this is a natural behavior of Flutter to lose data of a Stateful widget after navigating to another screen or there is something wrong with my code.

Can anybody help me with this

enter image description here

This is my code:

import "package:flutter/material.dart";
import "dart:async";
import "dart:convert";
import "package:http/http.dart" as http;

void main() {
  runApp(MovieApp());
}

class MovieApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'test',
        home: Scaffold(
            appBar: AppBar(
                backgroundColor: Colors.white,
                title: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[
                      Text("Top Movies List",
                          textDirection: TextDirection.rtl,
                          style: TextStyle(color: Colors.black87))
                    ]
                )
            ),
            body: MoviesList()
        )
    );
  }
}


class MoviesList extends StatefulWidget {
  @override
  MoviesListState createState() => new MoviesListState();
}

class MoviesListState extends State<MoviesList> {

  List moviesList = [];

  Future<Map> getData() async {
    http.Response response = await http.get(
        'http://api.themoviedb.org/3/discover/movie?api_key={api_key}'
    );
    setState(() {
        moviesList = json.decode(response.body)['results'];
    });
//    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    getData();
    if(moviesList == null) {
      return Scaffold(
        body: Text('Getting data from server')
      );
    } else {
      return ListView.builder(
          itemCount: moviesList.length,
          itemBuilder: (context, index){
            return Container(
                child: ListTile(
                    title: Text(moviesList[index]['title']),
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => MovieDetails()),
                      );
                    }
                )
            );
          }
      );
    }
  }
}

class MovieDetails extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('Details')
      ),
      body: Container(
          child: Center(
            child: RaisedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text('Go back!'),
            ),
          )
      ),
    );
  }
}

Upvotes: 3

Views: 2444

Answers (1)

diegoveloper
diegoveloper

Reputation: 103541

Move your getData() method inside the initState() in your State class. (Remove it from build method)

@override
 void initState() {
   getData();
   super.initState();
}

Upvotes: 1

Related Questions