text
stringlengths
1
80
@override
widget build(BuildContext context) {
return MaterialApp(
title: 'sample app',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});
@override
State<SampleAppPage> createState() => _SampleAppPageState();
}
class _SampleAppPageState extends State<SampleAppPage> {
// default placeholder text.
string textToShow = 'i like flutter';
void _updateText() {
setState(() {
// update the text.
textToShow = 'flutter is awesome!';
});
}
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('Sample app'),
),
body: center(child: Text(textToShow)),
floatingActionButton: FloatingActionButton(
onPressed: _updateText,
tooltip: 'update text',
child: const Icon(Icons.update),
),
);
}
}
<code_end>
<topic_end>
<topic_start>
how do i lay out my widgets? where is my XML layout file?
in android, you write layouts in XML, but in flutter you write your layouts
with a widget tree.
the following example shows how to display a simple widget with padding:
<code_start>
@override
widget build(BuildContext context) {
return scaffold(
appBar: AppBar(
title: const Text('Sample app'),
),
body: center(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.only(left: 20, right: 30),
),
onPressed: () {},
child: const Text('Hello'),
),
),
);
}
<code_end>
you can view some of the layouts that flutter has to offer in the
widget catalog.
<topic_end>
<topic_start>
how do i add or remove a component from my layout?
in android, you call addChild() or removeChild()
on a parent to dynamically add or remove child views.
in flutter, because widgets are immutable there is
no direct equivalent to addChild(). instead,
you can pass a function to the parent that returns a widget,
and control that child鈥檚 creation with a boolean flag.
for example, here is how you can toggle between two
widgets when you click on a FloatingActionButton:
<code_start>
import 'package:flutter/material.dart';
void main() {
runApp(const SampleApp());
}
class SampleApp extends StatelessWidget {
const SampleApp({super.key});
// this widget is the root of your application.
@override
widget build(BuildContext context) {
return MaterialApp(
title: 'sample app',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
),
home: const SampleAppPage(),
);
}
}
class SampleAppPage extends StatefulWidget {
const SampleAppPage({super.key});