본문 바로가기

Flutter/00 Legacy

[Flutter] Bloc, Stream - setState 로 구현

원본 영상(www.youtube.com/watch?v=2iWJRAcEsaQ&list=PLwUg6hFuXV86arSYNF9x_5Vm_lKdIBpf9&index=53)

 

main.dart

 

import 'package:bloc_stream/src/random_list.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: RandomList(),
    );
  }
}

 

random_list.dart

 

import 'package:bloc_stream/src/saved.dart';
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

class RandomList extends StatefulWidget {
  @override
  _RandomListState createState() => _RandomListState();
}

class _RandomListState extends State<RandomList> {
  final List<WordPair> _suggestions = <WordPair>[];
  final Set<WordPair> _saved = Set<WordPair>();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Naming App'),
        actions: <Widget>[
          IconButton(icon: Icon(Icons.list), onPressed: () {
          Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => SavedList(saved: _saved))
          ).then((value) {
            //저장화면에서 돌아오면 변경사항을 다시 그리기
            // Future/async/await 처리 안해도 됨.
            // 리턴시 처리 필요없음 return Future.value(true);
            setState(() {
            });
          });
        })],
      ),
      body: _buildList(),
    );
  }

  Widget _buildList() {
    return ListView.builder(itemBuilder: (context, index) {
      // 0,2,4,6,8 is real items
      // 1,3,5,7,9 is dividers
      if (index.isOdd) {
        return Divider();
      }
      // 몫을 구하는 방법, 파이썬은 // 2개로처리.
      var realIndex = index ~/ 2;
      if (realIndex >= _suggestions.length) {
        // 화면에 표시할 내용이 단어 개수보다 많으면(같거나) 단어를 10 추가 생성할것.
        _suggestions.addAll(generateWordPairs().take(10));
      }
      return _buildRow(_suggestions[realIndex]);
    });
  }

  Widget _buildRow(WordPair pair) {
    // 해당 단어가 저장되어 있는지 확인
    final bool alreadySaved = _saved.contains(pair);

    return ListTile(
      title: Text(
        pair.asPascalCase,
        textScaleFactor: 1.5,
      ),
      trailing: Icon(
        alreadySaved ? Icons.favorite : Icons.favorite_border,
        color: Colors.pinkAccent,
      ),
      onTap: () {
        setState(() {
          if (alreadySaved)
            _saved.remove(pair);
          else
            _saved.add(pair);
          print(_saved.toString());
        });
      },
    );
  }
}

 

saved.dart

 

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

class SavedList extends StatefulWidget {
  // 'saved' 리스트는 레퍼런스로 가져오기 때문에 여기서 삭제 가능 
  final Set<WordPair> saved;

  SavedList({@required this.saved});

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

class _SavedListState extends State<SavedList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Saved'),
      ),
      body: _buildList(),
    );
  }

  Widget _buildList() {
    return ListView.builder(
        itemCount: widget.saved.length * 2,
        itemBuilder: (context, index) {
          if (index.isOdd) return Divider();
          var realIndex = index ~/ 2;
          return _buildRow(widget.saved.toList()[realIndex]);
        });
  }

  Widget _buildRow(WordPair pair) {
    return ListTile(
      title: Text(
        pair.asPascalCase,
        textScaleFactor: 1.5,
      ),
      onTap: () {
        setState(() {
          // 'saved' 리스트는 레퍼런스로 가져오기 때문에 여기서 삭제 가능 
          widget.saved.remove(pair);
        });
      },
    );
  }
}