1

我是新手,我正在尝试一个简单的功能..
我有一个带有文本和凸起按钮的页面我想在每次按下按钮时将文本大小增加 1.0.. 我已经尝试过,但它不是在职的 ..

class _StoryDetailsState extends State<StoryDetails> {
@override
Widget build(BuildContext context) {
var textSize = 10.0;

return Scaffold(
  backgroundColor: Color(0xffEA3A82),
  appBar: AppBar(
    elevation: 0.0,
    backgroundColor: Color(0xffEA3A82),
    title: Text(widget.story_title),
  )
  ,body: SingleChildScrollView(
  child: Column(
    children: <Widget>[
      Align(
          alignment: Alignment.topLeft
          ,child: Image.network(widget.story_detail_pic , width: double.infinity,)
      ),

      RaisedButton(
        child: Text('enlarge text'),
        onPressed: (){
          setState(() {
            textSize = textSize + 1.0;
            print(textSize); 
          });
        },
      ),
      Padding(
        padding: const EdgeInsets.all(10.0),
        child: ClipRRect(borderRadius: BorderRadius.circular(10)
            ,child: Container(color: Colors.white.withOpacity(0.6) ,child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text(widget.story , style: TextStyle(fontSize: textSize),),
            ))),
      )
    ],
  ),
),
);
 } 
}
4

1 回答 1

1

问题是您textsize在构建方法内部声明。每次调用 set state 时,都会调用 build 方法,并将 yourtextsize再次设置为 10。只需移出var textSize = 10.0;构建方法,它就会正常工作。

class _StoryDetailsState extends State<StoryDetails> {
  var textSize = 10.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xffEA3A82),
      appBar: AppBar(
        elevation: 0.0,
        backgroundColor: Color(0xffEA3A82),
        title: Text("Title"),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Align(
                alignment: Alignment.topLeft,
                child: Image.network(
                  "http://via.placeholder.com/640x360",
                  width: double.infinity,
                )),
            RaisedButton(
              child: Text('enlarge text'),
              onPressed: () {
                textSize = textSize + 1.0;
                print(textSize);
                setState(() {});
              },
            ),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Container(
                      color: Colors.white.withOpacity(0.6),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "story",
                          style: TextStyle(fontSize: textSize),
                        ),
                      ))),
            )
          ],
        ),
      ),
    );
  }
}
于 2019-09-12T15:55:48.133 回答