僕に捧ぐ

個人開発者の備忘録と雑談です。

Flutterでボタンを押下するとウィジェットが増えて行く画面を作りたかった。(続き)

昨日書いた記事の続きです。

floatingActionButton を使ってみる

floatingActionButtonは右下に表示されるボタンです。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> list = <Widget>[
    Container(
      child: Text( "Hello! Flutter!",
        style: TextStyle(fontSize:32.0,
            color: const Color(0xFF000000),
            fontWeight: FontWeight.w200,
            fontFamily: "Roboto"),
      ),
      padding: const EdgeInsets.all(10.0),
      alignment: Alignment.bottomCenter,
    ),
  ];

  List<Widget> _items = <Widget>[];

  @override
  void initState(){
    super.initState();
    _items = list;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body:
      ListView.builder(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index){
          return _items[index];
        },
        itemCount: _items.length,
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: buttonPressed,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  void buttonPressed(){
    list.add(
      Container(
        child: Text( "Hello! Flutter!",
          style: TextStyle(fontSize:32.0,
              color: const Color(0xFF000000),
              fontWeight: FontWeight.w200,
              fontFamily: "Roboto"),
        ),
        padding: const EdgeInsets.all(10.0),
        alignment: Alignment.bottomCenter,
      ),
    );

    setState((){
      _items = list;
    });
  }
}

こんな感じになります。

f:id:kohshin1977:20191012100801p:plain:w250

ボタンを押下していくと増えていってスクロールもできるようになりました!

f:id:kohshin1977:20191012101221p:plain:w250

以上です。