StatefulWidgetを使った人気投票


import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  MyApp({Key? key}) : super(key: key);
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  var like = [0,0,0];
  var name = ['소영', '임콩', '봉태'];

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar( title: Text('인기쟁이 뽑기'),),
        body: ListView.builder(
          itemCount: 3,
          itemBuilder: (c, i){
            return ListTile(
              leading: Text(like[i].toString()),
              title: Text(name[i]),
              trailing: ElevatedButton(
                child: Text('좋아요'),
                onPressed: (){
                  setState(() {
                    like[i]++;
                  });
                },
              )
            );
          },
        ),
      )
    );
  }
}

人気豆