Simple Riverpod example beyond the counter app: sum of two cells

Viewed 510

I'm learning Flutter and I'm stuck on state management. I took a look at Riverpod and it looks promising, but I have a hard time to go beyond the counter app to something more complicated.

For example, I want to have two TextFields that collect numbers, and another Text widget to display the sum of the two TextField values. Here's what I have.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main() {
  runApp(ProviderScope(
    child: MyApp(),
  ));
}

class MyApp extends HookWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(title: 'Adding two cells'),
    );
  }
}

final cellProvider = StateProvider((_) => <int>[0, 0]);

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Consumer(builder: (context, watch, _) {
        print(watch(cellProvider).state);
        num _sum = watch(cellProvider).state[0] + watch(cellProvider).state[1];
        return Center(
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Cell(0),
                  Cell(1),
                ],
              ),
              SizedBox(
                height: 100,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text('Sum: ${_sum.toString()}'),
                ],
              ),
            ],
          ),
        );
      }),
    );
  }
}

class Cell extends HookWidget {
  Cell(this.index);
  final int index;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 150,
      padding: EdgeInsets.all(30),
      child: TextField(
        inputFormatters: [FilteringTextInputFormatter.digitsOnly],
        onChanged: (value) {
          context.read(cellProvider).state[index] = num.tryParse(value);
        },
      ),
    );
  }
}

The Text widget does not update. Any suggestion?

Thank you very much, Tony

1 Answers

The provider only updates when the object it provides changes, just as a Stream returns a final value you need to update the whole object (List<int>) so the consumer updates properly, changing inner values of an iterable won't trigger an update

onChanged: (value) {
   final List<int> myList = context.read(cellProvider).state;
   myList[index] = num.tryParse(value); 
   context.read(cellProvider).state = myList; //update the state with a new list
},
Related