Flutter中Column内长文本滚动实现求助:适配API动态内容
Hey there! Let's get that long dynamic text working properly in your Column. The overflow error you're seeing happens because unconstrained Text widgets try to take as much vertical space as they need—way more than the screen can fit when the content is super long. Here's a straightforward solution that works perfectly with dynamic API data:
Step-by-Step Fix
Wrap your long Text widget in a SingleChildScrollView, and use Expanded to give it a constrained height within your Column. This ensures the scrollable text area only takes up the remaining screen space after your image and title, while still letting users scroll through the full content.
Working Code Example
@override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ // Your top image (dynamic URL from API works here) Image.network('https://your-api-image-url.com/image.jpg'), // Title Text (dynamic from API too) Padding( padding: EdgeInsets.symmetric(vertical: 12.0), child: Text( apiData.title, style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold), ), ), // Scrollable long text section Expanded( child: SingleChildScrollView( padding: EdgeInsets.symmetric(horizontal: 16.0), child: Text( apiData.longDescription, // Dynamic text from your API style: TextStyle(fontSize: 16, height: 1.5), ), ), ), ], ), ); }
Why This Works
Expanded: Tells theSingleChildScrollViewto occupy only the remaining vertical space in the Column, so it doesn't push your image and title off-screen or cause infinite height errors.SingleChildScrollView: Handles all the scrolling logic automatically—no matter how long the API-provided text is, users can scroll to see every word without overflow issues.- Dynamic Data Ready: Since we're pulling
titleandlongDescriptiondirectly from your API data object, this setup will adapt seamlessly to whatever content comes in.
Common Mistake to Avoid
Don't forget the Expanded! If you put SingleChildScrollView directly in the Column without it, the ScrollView will try to take an infinite amount of vertical space, which will throw the same overflow error you're seeing now.
内容的提问来源于stack exchange,提问作者Vaibhav Miniyar

