0
0

More than 3 years have passed since last update.

【Flutter】GridViewをスクロールするとStateがデフォルトに戻る件

Posted at

Flutterに詳しい方、是非教えていただきたいです。

写真・メッセージ・値段・カウントの要素を持ったコンポーネントをリストにまとめました。
要素のカウント部分は、ボタンプッシュにより数が増減するようになっています。
それをGridViewで表示させています。

表示まではうまくいったのですが、増減させたはずのカウントがスクロールにより画面から外れると、デフォルト値に戻ってしまいます。

GridViewのcacheExtentを増やすことで防げるのですが、Listの数は可変にしたいので、キャッシュ値を固定化することは避けたいです。

キャッシュ値を変更する以外で、スクロールから外れてもカウントが維持できる方法はありますでしょうか。

/* root.dart */

import 'package:flutter/material.dart';
import 'pages/loading.dart'; /*ソース省略*/
import 'pages/home.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'title',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: '/home',
      routes: {
        '/': (context) => Loading(),
        '/home': (context) => Home(),
      },
    );
  }
}


/* pages/m_list.dart */

class MList {
  String name;
  int price;
  var pic;

  MList({this.name, this.price, this.pic});
}
/* pages/home.dart */

import 'package:flutter/material.dart';
import './m_list.dart';
import './comp.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  final List<MList> orders = [
    MList(pic: 'assets/IMG_1.jpeg', name: 'text1', price: 300),
    MList(pic: 'assets/IMG_2.jpeg', name: 'text2', price: 500),
    MList(pic: 'assets/IMG_3.jpeg', name: 'text3', price: 500),
    MList(pic: 'assets/IMG_4.jpeg', name: 'text4', price: 500),
  ];

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

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('text'),
        backgroundColor: Colors.orange[500],
      ),
      body: GridView.count(
        scrollDirection: Axis.vertical,
        crossAxisCount: 1,
        children: orders.map((order) => Comp(order.pic, order.name, order.price)).toList(),
      ),
    );
  }
}

/* pages/comp.dart */

import 'package:flutter/material.dart';
import './m_list.dart';

class Comp extends StatefulWidget {
  final pic;
  final name;
  final price;

  Comp(this.pic, this.name, this.price);

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

class _CompState extends State<Comp> {
  int _counter = 0;
  MList order;

  void _countUp() {
    setState(() {
      _counter++;
    });
  }

  void _countDown() {
    setState(() {
      if (_counter > 0) {
        _counter--;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.grey[200],
      margin: EdgeInsets.all(10.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
              flex: 4,
              child: Container(
                  width: double.infinity,
                  child: Image.asset(
                    widget.pic,
                    fit: BoxFit.fitWidth,
                  ))),
          Expanded(
              flex: 2,
              child: Text(
                widget.name,
                style: TextStyle(fontSize: 14.0),
              )),
          Expanded(
            flex: 1,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Text(
                  widget.price.toString() + '円',
                  style: TextStyle(fontSize: 14.0),
                ),
                Row(
                  children: <Widget>[
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: FlatButton(
                        padding: EdgeInsets.all(0),
                        color: Colors.orange[200],
                        onPressed: () {
                          _countUp();
                        },
                        child: Text(
                          '+',
                          style: TextStyle(fontSize: 20.0),
                        ),
                      ),
                    ),
                    Text(
                      ' $_counter ',
                      style: TextStyle(fontSize: 16.0),
                    ),
                    SizedBox(
                      width: 40,
                      height: 40,
                      child: FlatButton(
                        padding: EdgeInsets.all(0),
                        color: Colors.orange[200],
                        onPressed: () {
                          _countDown();
                        },
                        child: Text(
                          '-',
                          style: TextStyle(fontSize: 20.0),
                        ),
                      ),
                    )
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

よろしくお願いします。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0