【Flutter/Dart】for文/繰り返し文の使い方/基礎から実践
Dartの基本文であるfor文について調べてまとめました。基礎から実践までサンプルがあります。動かない場合はコメントください。
動かすにはDartpadを使用してください。
目次
for文とは
公式サイト
https://dart.dev/guides/language/language-tour#for-loops
for文とは条件の範囲内であれば繰り返し処理を行える文でDartでも使用することができます。
他に繰り返し文には
- while
- do-while
文があります。
細かい分類としてfor文には
- for…in
- forEach
文があります。
基礎
for文
ちょっとした解説
int i=0で、iを初期化します。次にi>10にして、10回までループさせます。最後に、i++でループ毎にiのカウントをプラスしていきます。
void main() { for (int i = 0; i < 5; i++) { print('hello${i + 1}'); } }
ちょっとした解説
${}をつけることにより、変数と文字列を同時に出力することができます。
for…in文
for…in文は変数に格納された(SetやMap/List)を出力させるために使います。
変数内に格納されている全てのデータを左から順に宣言した変数に代入し処理中で使用できます。
配列のデータ全てを取得し処理を終えるとループ処理が終了します。
void main() { var mixFruit = ['apple', 'banana', 'grape']; for (var fruit in mixFruit) { print(fruit); } print('Loopから脱出'); }
forEach文
List/Setの使用する場合
void main(){ var mixFruit = ['apple', 'banana', 'grape']; mixFruit.forEach((fruit){ print(fruit); } ); print('Loopから脱出'); }
void main() { var numbers = [1, 2, 3, 4, 5]; numbers.forEach((num) { print(num); }); }
Mapで使用する場合
void main() { var ages = { 'Alex': 18, 'Ben': 15, 'Charlie': 25, }; ages.forEach((name, age) { print("${name} is ${age} years old"); }); print('Loopから脱出'); }
余談
余談ですが、SetやMapを使用するときは変数に置き換えて書くことが可能です。
https://api.flutter.dev/flutter/dart-core/Map-class.html
実践
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); static const String _title = 'for文'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: Scaffold( appBar: AppBar(title: const Text(_title)), body: const MyStatelessWidget(), ), ); } } class MyStatelessWidget extends StatelessWidget { const MyStatelessWidget({Key? key}) : super(key: key); @override Widget build(BuildContext context) { const moviesTitles = ['Inception', 'Heat', 'Spider Man']; return Column( children: moviesTitles.map((title) => Tab(text: title)).toList(), ); } }
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); static const String _title = 'BottomNavBar Code Sample'; @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: _title, home: MyStatefulWidget(), ); } } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({Key? key}) : super(key: key); @override State<MyStatefulWidget> createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { int _selectedIndex = 0; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('BottomNavigationBar Sample'), ), body: Center( child: Column( mainAxisSize: MainAxisSize.min, children:<Widget> [ Text( "indexNum: $_selectedIndex", style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold), ), for(int i = 0; i < 5; i++) ... { Text('${i}番目のループ。navigationbar${_selectedIndex}です。') },]) ), bottomNavigationBar: BottomNavigationBar( currentIndex: _selectedIndex, onTap: _onItemTapped, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.book), activeIcon: Icon(Icons.book_online), label: 'Book', tooltip: "This is a Book Page", backgroundColor: Colors.blue, ), BottomNavigationBarItem( icon: Icon(Icons.business), activeIcon: Icon(Icons.business_center), label: 'Business', tooltip: "This is a Business Page", backgroundColor: Colors.green, ), BottomNavigationBarItem( icon: Icon(Icons.school), activeIcon: Icon(Icons.school_outlined), label: 'School', tooltip: "This is a School Page", backgroundColor: Colors.purple, ), BottomNavigationBarItem( icon: Icon(Icons.settings), activeIcon: Icon(Icons.settings_accessibility), label: 'Settings', tooltip: "This is a Settings Page", backgroundColor: Colors.pink, ), ], type: BottomNavigationBarType.shifting, // ここで色を設定していても、shiftingにしているので // Itemの方のbackgroundColorが勝ちます。 backgroundColor: Colors.red, enableFeedback: true, // IconTheme系統の値が優先されます。 iconSize: 18, // 横向きレイアウトは省略します。 // landscapeLayout: 省略 selectedFontSize: 20, selectedIconTheme: const IconThemeData(size: 30, color: Colors.green), selectedLabelStyle: const TextStyle(color: Colors.red), // ちなみに、LabelStyleとItemColorの両方を選択した場合、ItemColorが勝ちます。 selectedItemColor: Colors.black, unselectedFontSize: 15, unselectedIconTheme: const IconThemeData(size: 25, color: Colors.white), unselectedLabelStyle: const TextStyle(color: Colors.purple), // IconTheme系統の値が優先されるのでこの値は適応されません。 unselectedItemColor: Colors.red, ), ); } }
参考
https://note.com/hatchoutschool/n/na654d6dc5a53
https://zenn.dev/kenghaya/articles/170fde921faf60
https://flutternyumon.com/how-to-use-for-loop/#for-in%E6%96%87