【赠书第7期】从零基础到精通Flutter开发
在学习任何新技术时,理论知识是基础,实践项目是提升。以下是一个简单的Flutter项目,用于创建一个简单的计算器应用程序。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CalculatorHome(),
);
}
}
class CalculatorHome extends StatefulWidget {
@override
_CalculatorHomeState createState() => _CalculatorHomeState();
}
class _CalculatorHomeState extends State<CalculatorHome> {
String _result = "0";
String _operation = "";
bool _clearNeeded = false;
void _clear() {
setState(() {
_result = "0";
_operation = "";
_clearNeeded = false;
});
}
void _operationPressed(String operation) {
setState(() {
if (_operation != "") {
_result = _calculate(_result, _operation);
}
_operation = operation;
_clearNeeded = true;
});
}
void _digitPressed(String digit) {
setState(() {
if (_clearNeeded) {
_result = digit;
_clearNeeded = false;
} else if (_result == "0") {
_result = digit;
} else {
_result += digit;
}
});
}
String _calculate(String a, String operation) {
var calc = Calculator();
switch (operation) {
case '+':
return calc.add(double.parse(a), double.parse(_result)).toString();
case '-':
return calc.subtract(double.parse(a), double.parse(_result)).toString();
case '*':
return calc.multiply(double.parse(a), double.parse(_result)).toString();
case '/':
if (_result != "0") {
return calc.divide(double.parse(a), double.parse(_result)).toString();
} else {
return "Can't divide by 0";
}
default:
return "Error";
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_result,
style: TextStyle(
fontSize: 32.0,
color: Colors.black,
),
),
Row(
mainAxisAlignment: MainAxisAlign
评论已关闭