text
stringlengths
1
80
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
// default value for toggle.
bool toggle = true;
void _toggle() {
setState(() {
toggle = !toggle;
});
}
widget _getToggleChild() {
if (toggle) {
return const Text('Toggle one');
} else {
return ElevatedButton(
onPressed: () {},
child: const Text('Toggle two'),
);
}
}
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('Sample app'),
),
body: center(
child: _getToggleChild(),
),
floatingActionButton: FloatingActionButton(
onPressed: _toggle,
tooltip: 'update text',
child: const Icon(Icons.update),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
how do i animate a widget?
in android, you either create animations using XML, or call the animate()
method on a view. in flutter, animate widgets using the animation
library by wrapping widgets inside an animated widget.
in flutter, use an AnimationController which is an animation<double>
that can pause, seek, stop and reverse the animation. it requires a ticker
that signals when vsync happens, and produces a linear interpolation between
0 and 1 on each frame while it’s running. you then create one or more
animations and attach them to the controller.
for example, you might use CurvedAnimation to implement an animation
along an interpolated curve. in this sense, the controller
is the “master” source of the animation progress and the CurvedAnimation
computes the curve that replaces the controller’s default linear motion.
like widgets, animations in flutter work with composition.
when building the widget tree you assign the animation to an animated
property of a widget, such as the opacity of a FadeTransition, and tell the
controller to start the animation.
the following example shows how to write a FadeTransition that fades the
widget into a logo when you press the FloatingActionButton:
<code_start>
import 'package:flutter/material.dart';
void main() {
runApp(const FadeAppTest());
}
class FadeAppTest extends StatelessWidget {
const FadeAppTest({super.key});
// this widget is the root of your application.
@override
widget build(BuildContext context) {
return MaterialApp(
title: 'fade demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const MyFadeTest(title: 'fade demo'),
);
}
}
class MyFadeTest extends StatefulWidget {
const MyFadeTest({super.key, required this.title});
final string title;
@override
State<MyFadeTest> createState() => _MyFadeTest();
}
class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin {
late AnimationController controller;
late CurvedAnimation curve;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: const duration(milliseconds: 2000),
vsync: this,
);
curve = CurvedAnimation(
parent: controller,
curve: Curves.easeIn,
);
}