はじめに
プログレスバーをFlutterで作ってみます。
※一部コードを省略していますので、ご注意ください。
完成形イメージ
こんな感じで、「次へ」ボタンを押すと5分の1ずつ増加させて、端までいったら最初に戻します。
LinearProgressIndicatorを使用する
LinearProgressIndicatorで作っていきます。
完成形のコード
コードはこちら↓
questionnaire.dart
import 'package:flutter/material.dart';
class QuestionnairePage extends StatefulWidget {
@override
_QuestionnairePageState createState() => _QuestionnairePageState();
}
class _QuestionnairePageState extends State<QuestionnairePage> {
double _progress = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('アンケート'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(30)),
child: LinearProgressIndicator(
backgroundColor: Colors.grey,
valueColor: new AlwaysStoppedAnimation<Color>(Colors.lightBlueAccent),
minHeight: 30,
value: _progress,
),
),
ElevatedButton(
child: Text('次へ'),
onPressed: () {
setState(() {
if (_progress == 1.0) {
_progress = 0;
} else {
_progress += 0.2;
}
});
},
),
],
),
),
),
);
}
}
ポイント① ボタンを押したら進行させる
- _progress で制御しており、1.0で端までいく
- _progress += 0.2 を変更することで任意のサイズにできる
double _progress = 0;
...
child: LinearProgressIndicator(
...
value: _progress,
),
...
ElevatedButton(
...
onPressed: () {
setState(() {
if (_progress == 1.0) {
_progress = 0;
} else {
_progress += 0.2;
}
});
},
),
...
ポイント② バーの大きさを変更
- LinearProgressIndicator内のminHeightで設定
ポイント③ バーの色を変更
- LinearProgressIndicator内のbackgroundColorとvalueColorを設定
backgroundColor: Colors.grey, // 背景色
valueColor: new AlwaysStoppedAnimation<Color>(Colors.lightBlueAccent),
ポイント④ バーに丸みをつける
- LinearProgressIndicatorをClipRRectで囲う
- borderRadiusを使用する
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(30)), // ここで丸みを調整
child: LinearProgressIndicator(
...
参考にさせていただいたサイト
- LinearProgressIndicator class
- Flutter - Using LinearProgressIndicator Examples
- 【Flutter】ClipRRectを使ってウィジェットを角丸にする
おわりに
ここまで読んでいただきありがとうございました!何かありましたらコメントをお願いします。