首页 > 解决方案 > flutter int got to zero

问题描述

I have a screen with a one button and anotherone with a Container to show a number. I declared a variable in the StatlessWidget class. The button adds 1 to the variable , however after leaving the Class with the container und return to it, I noticed the widgets get updated and my variable loses its value. I have tried initializing it in initState() but it still loses it's value.

import 'package:flutter/material.dart';
import 'package:generator/route_generator.dart';
import 'package:generator/main.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/menu',
      onGenerateRoute: RouteGenerator.generateRoute,
    );
  }
}

class Menu extends StatelessWidget {
  int data = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Menu'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              RaisedButton(
                onPressed: () {
                  Navigator.of(context).pushNamed('/second', arguments: data);
                },
                child: Text('go to the second'),
              ),
            ],
          ),
        ));
  }
}

class FirstPage extends StatelessWidget {
  int data = 0;

  void eins() {
    data = data + 25;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('First Page'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                data.toString(),
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                  Navigator.of(context).pushNamed('/second', arguments: data);
                },
                child: Text('go to the second'),
              ),
              RaisedButton(
                child: Text('25'),
                onPressed: eins,
              )
            ],
          ),
        ));
  }
}

class SecondPage extends StatelessWidget {
  int data = 0;
  SecondPage({Key key, @required this.data}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Second Page'),
        ),
        body: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                data.toString(),
                style: TextStyle(fontSize: 20),
              ),
              RaisedButton(
                onPressed: () {
                  Navigator.of(context).pushNamed('/first');
                },
                child: Text('go to the first'),
              ),
            ],
          ),
        ));
  }
}

another class

import 'package:flutter/material.dart';
import 'package:generator/main.dart';
import './main.dart';

class RouteGenerator {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    final args = settings.arguments;

    switch (settings.name) {
      case '/first':
        return MaterialPageRoute(
          builder: (_) => FirstPage(),
        );
      case '/third':
        return MaterialPageRoute(
          builder: (_) => FirstPage(),
        );
      case '/menu':
        return MaterialPageRoute(
          builder: (_) => Menu(),
        );

      case '/second':
        // if (args is int) {
        return MaterialPageRoute(
          builder: (_) => SecondPage(
            data: args,
          ),
        );
      //}

      // return _errorRoute();
      //default:
      //return _errorRoute();
    }
  }

  static Route<dynamic> _errorRoute() {
    return MaterialPageRoute(builder: (_) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Error'),
        ),
        body: Center(
          child: Text('ERROR'),
        ),
      );
    });
  }
}

标签: flutterdartinteger

解决方案


The first thing that is weird about your program is that you want to preserve state, in your case a counter variable, but to do that, you select a StatelessWidget. At the very least you will need a StatefulWidget. It's in the name already.

That said, it's not that easy, you may want to look up the different approaches to state management in Flutter: https://flutter.dev/docs/development/data-and-backend/state-mgmt/options


推荐阅读